package com.asiainfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.StringTokenizer;

import org.junit.Assert;

public class JNIHexUtil {

	private static final int count = 10000;

	static {
		try {
			String libpath = System.getProperty("java.library.path");
			if (libpath == null || libpath.length() == 0) {
				throw new RuntimeException("java.library.path is null");
			}
			String path = null;
			StringTokenizer st = new StringTokenizer(libpath, System.getProperty("path.separator"));
			if (st.hasMoreElements()) {
				path = st.nextToken();
			} else {
				throw new RuntimeException("can not split library path:" + libpath);
			}
			InputStream inputStream = JNIHexUtil.class.getResource("/jni.dll").openStream();
			File dllFile = new File(new File(path), "jni.dll");
			if (!dllFile.exists()) {
				FileOutputStream outputStream = new FileOutputStream(dllFile);
				byte[] array = new byte[8192];
				for (int i = inputStream.read(array); i != -1; i = inputStream.read(array)) {
					outputStream.write(array, 0, i);
				}
				outputStream.close();
			}
			System.loadLibrary("jni");
		} catch (UnsatisfiedLinkError e) {
			throw e;
		} catch (Throwable e) {
			throw new RuntimeException("load jni.dll error!", e);
		}
	}

	/**
	 * bytes转换成十六进制字符串
	 * 
	 * @param bytes
	 * @return
	 */
	public native static String byte2HexStr(byte[] bytes);

	public static void main(String[] args) throws Throwable {
		String testStr = "中文abc";

		// testStr = makeContentByLoop();

		byte[] bytes = testStr.getBytes();

		Assert.assertEquals(BytesHexStrUtil.byte2HexStr(bytes), byte2HexStr(bytes));

		// test(bytes);

	}

	private static void test(byte[] bytes) {
		{
			long b = System.currentTimeMillis();
			for (int i = 0; i < count; i++) {

			}
			System.out.println("jni耗时 " + (System.currentTimeMillis() - b));
		}

		{
			long b = System.currentTimeMillis();
			for (int i = 0; i < count; i++) {
				BytesHexStrUtil.byte2HexStr(bytes);
			}
			System.out.println("java耗时 " + (System.currentTimeMillis() - b));
		}
	}

	private static String makeContentByLoop() {
		StringBuilder test = new StringBuilder();
		for (int i = 0; i < count; i++) {
			test.append("中文中文中文中文中文中文中文中文中文中文中文中文中文中文中文中文中文中文中文中文中文中文中文中文");
		}
		return test.toString();
	}

}
